package org.koyad.portal.tags.piston;

import java.util.Map;

import org.koyad.portal.annotations.TagCordinates;
import org.koyad.portal.annotations.TagType;
import org.koyad.portal.api.BaseAction;
import org.koyad.portal.constants.FrameworkConstants;
import org.koyad.portal.context.PistonContext;
import org.koyad.portal.tags.AbstractTag;
import org.koyad.portal.tags.ViewRoot;
import org.koyad.portal.utils.LogUtils;

@TagCordinates (
	uri = FrameworkConstants.PORTAL_NAMESPACE,
	localName = "tile",
	type = TagType.NOBODY
)
public class TileTag extends AbstractTag {
	
	private static final LogUtils LOGGER = LogUtils.getLogger(TileTag.class);
	
	@Override
	public void postInit() {
		PistonContext pistonCtx = PistonContext.getContext();
		Map<String, String> actions = (Map<String, String>) pistonCtx.getApplication().getAttribute(FrameworkConstants.PISTON_ACTIONS);
		String action = actions.get(getAttributeValue(FrameworkConstants.PISTON_START_ACTION));
		
		try {
			Class actionClass = Class.forName(action);
			BaseAction bAction = (BaseAction)actionClass.newInstance();
			PistonContext.getContext().getViewRoot().setCurrentTile(this);
			bAction.execute();
			PistonContext.getContext().getViewRoot().resetCurrentTile(this);
		} catch (ClassNotFoundException e) {
			handleException(e);
		} catch (InstantiationException e) {
			handleException(e);
		} catch (IllegalAccessException e) {
			handleException(e);
		}
	}
	
	@Override
	protected void startTag() {
		
		StringBuffer buffer = new StringBuffer(_preStartTagText + "<");
		buffer.append("div");

		writeAttributes(buffer);

		buffer.append(">");

		buffer.append(_bodyText);
		
		getWriter().write(buffer.toString());
	}
	
	@Override
	protected void renderBody() {
		ViewRoot viewRoot = PistonContext.getContext().getViewRoot();
		AbstractTag tileFragment = viewRoot.getTileContent(this);
		
		viewRoot.setCurrentTile(this);
		tileFragment.render();
		viewRoot.resetCurrentTile();
	}
	
	@Override
	protected void closeTag() {
		getWriter().write(_preEndTagText + "</div>");
	}
	
	private void handleException(Exception e) {
		LOGGER.logException(e);
//		try {
////			FilterUtils.include("/Error.html");
//		} catch (ServletException e1) {
//			LOGGER.info("UNHANDLED EXCEPTION THROWN");
//		} catch (IOException e1) {
//			LOGGER.info("UNHANDLED EXCEPTION THROWN");
//		}
	}
}
